package com.zb.mvc.controller.sys;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.druid.sql.visitor.functions.Now;
import com.zb.dao.ext.base.OmsStoreFileDao;
import com.zb.dao.ext.charger.OmsChargerDao;
import com.zb.entity.base.JsonForList;
import com.zb.entity.base.OmsStoreFile;
import com.zb.entity.station.OmsStation;
import com.zb.service.sys.QiniuService;
import com.zb.util.PrimaryGenerater;
import com.zb.util.StringUtil;
import com.zb.util.serialGenerater;



@Controller
@RequestMapping("/file")
public class PhotoController { 
	@Autowired
	QiniuService qiniuService;
	
	@RequestMapping("/uploadtest")
	public String uploadtest(@RequestParam("file") CommonsMultipartFile[] files,HttpServletRequest request){
		
		for(int i = 0;i<files.length;i++){
			System.out.println("fileName---------->" + files[i].getOriginalFilename());
		
			if(!files[i].isEmpty()){
				int pre = (int) System.currentTimeMillis();
				try {
					//拿到输出流，同时重命名上传的文件
					FileOutputStream os = new FileOutputStream("d:/photo/" + new Date().getTime() + files[i].getOriginalFilename());
					//拿到上传文件的输入流
					FileInputStream in = (FileInputStream) files[i].getInputStream();
					
					//以写字节的方式写文件
					int b = 0;
					while((b=in.read()) != -1){
						os.write(b);
					}
					os.flush();
					os.close();
					in.close();
					int finaltime = (int) System.currentTimeMillis();
					System.out.println(finaltime - pre);
					
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("上传出错");
				}
		}
		}
		return "/success";
	}
	
	
	@RequestMapping("/upload"	)
	@ResponseBody
	public JsonForList upload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
		//创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		JsonForList json = new JsonForList();

		//判断 request 是否有文件上传,即多部分请求
		if(multipartResolver.isMultipart(request)){
			//转换成多部分request  
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;

            //所属系统app、oms：对应表名entity_tbl
			String entity_tbl = multiRequest.getParameter("entity_tbl");
			//对应entity_id
			String entity_id = multiRequest.getParameter("entity_id");
			
			HttpSession session = request.getSession();
			//操作人员ID
			String create_oper_id = (String) session.getAttribute("login_oper_id");
			Date date = new Date();
			//服务器临时存储路径
			String localPpath = this.getClass().getClassLoader().getResource("").getPath();
			//上传七牛云结果集：返回前端
			List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>(); 			
		    ////上传七牛云结果集：数据库存储
			List<OmsStoreFile> list = new ArrayList<OmsStoreFile>();
			//取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			
			while(iter.hasNext()){
				//记录上传过程起始时的时间，用来计算上传时间
				int pre = (int) System.currentTimeMillis();
				//取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if(file != null){
					//取得当前上传文件的文件名称
					String myFileName = file.getOriginalFilename();
					//如果名称不为“”,说明该文件存在，否则说明该文件不存在
					if(myFileName.trim() !=""){
						//重命名上传后的文件名
						String fileName = "oms"+addZeroForString(file.getOriginalFilename(),6);
						//定义上传路径
						String path = localPpath + fileName;
						File localFile = new File(path);
						file.transferTo(localFile);
						
						if(file.getSize() > 1024 * 1024 * 5){
							Map map = new HashMap<String, Object>();  
							map.put("filename", file.getOriginalFilename());
							map.put("uploadresult", "文件超过5M!");
							resultList.add(map);
							continue;
						}else if (qiniuService.upload(path,fileName)){
							//上传成功后删除文件
							localFile.delete();
							
							Map map = new HashMap<String, Object>();  
							map.put("filename", file.getOriginalFilename());
							map.put("uploadresult", "200");
							resultList.add(map);
						
							OmsStoreFile omsStoreFile = new OmsStoreFile();
							Random random = new Random(1213);  
							omsStoreFile.setFile_id(serialGenerater.generateSerialNo());
							omsStoreFile.setFile_name(file.getOriginalFilename());  //上传时的文件名。
							omsStoreFile.setRemote_file_name(fileName);  //远程文件名称包括文件路径
							omsStoreFile.setDownload_path("");  //这里的文件路径表示，正式外网可以访问到文件路径，就是下载链接
							omsStoreFile.setFilename_extension(file.getContentType());//文件扩展名
							omsStoreFile.setCreate_oper_id(create_oper_id);
							omsStoreFile.setCreate_time(date);
							omsStoreFile.setValid_flag("1");
							omsStoreFile.setEntity_tbl(entity_tbl);
							omsStoreFile.setEntity_id(entity_id);
							omsStoreFile.setFile_function("");
							
							list.add(omsStoreFile);
						}else {
							//上传成功后删除文件
							localFile.delete();
							
							Map map = new HashMap<String, Object>();  
							map.put("filename", file.getOriginalFilename());
							map.put("uploadresult", "上传七牛云失败!");
							resultList.add(map);
						}
						
					}
				}
				//记录上传该文件后的时间
				int finaltime = (int) System.currentTimeMillis();
				System.out.println(finaltime - pre);
			}
			//保存
			qiniuService.saveOmsStoreFile(list);
			
			json.setList(resultList);
		}
		
		json.setCode(JsonForList.SuccessCode);
		return json;
	}
	
	@RequestMapping("/download"	) 
	@ResponseBody
	public JsonForList download(HttpServletRequest request,HttpServletResponse response) {
		//所属系统app、oms：对应表名entity_tbl
		String entity_tbl = request.getParameter("entity_tbl");
		//对应entity_id
		String entity_id = request.getParameter("entity_id");
		
		List<OmsStoreFile> list = (List<OmsStoreFile>) qiniuService.getOmsStoreFileList(entity_tbl,entity_id,null);
		List<String> listDownloadUrl = new ArrayList<String>();
		for(OmsStoreFile omsStoreFile:list)  
        {  
			listDownloadUrl.add(qiniuService.download(omsStoreFile.getRemote_file_name()));
        }
		
		JsonForList json = new JsonForList();
		json.setList(listDownloadUrl);
		json.setCode(JsonForList.SuccessCode);
		return json;
	}
	
	@RequestMapping("/delete"	) 
	@ResponseBody
	public JsonForList delete(HttpServletRequest request,HttpServletResponse response) {
		//所属系统app、oms：对应表名entity_tbl
		String entity_tbl = request.getParameter("entity_tbl");
		//对应entity_id
		String entity_id = request.getParameter("entity_id");
		//对应entity_id
		String remote_file_names = request.getParameter("remote_file_names");
		//删除结果集：返回前端
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (StringUtil.isNotBlank(remote_file_names)) {
			List<OmsStoreFile> list = (List<OmsStoreFile>) qiniuService.getOmsStoreFileList(entity_tbl,entity_id,remote_file_names);		
			for(OmsStoreFile omsStoreFile:list)  
	        {  
				if (qiniuService.delete(omsStoreFile.getRemote_file_name())) {
					qiniuService.logicDelete(omsStoreFile);
					
					Map map = new HashMap<String, Object>();  
					map.put("filename", omsStoreFile.getRemote_file_name());
					map.put("deleteResult", "200");
					resultList.add(map);
				}else {
					Map map = new HashMap<String, Object>();  
					map.put("filename", omsStoreFile.getRemote_file_name());
					map.put("deleteResult", "七牛云删除失败!");
					resultList.add(map);
				}
				
	        }
		}else{
			JsonForList json = new JsonForList();
			json.setCode(JsonForList.FailCode);
			json.setMsg("remote_file_names can not null or empty!");
			return json;
		}
	
		JsonForList json = new JsonForList();
		json.setList(resultList);
		json.setCode(JsonForList.SuccessCode);
		return json;
	}
	
	public String addZeroForString(String str, int strLength) {
	     int strLen = str.length();
	     StringBuffer sb = null;
	     if (strLen>=strLength) {
			str=str.substring(strLen-strLength);
		}else{ 
			while (strLen < strLength) {
	           sb = new StringBuffer();
	           sb.append("0").append(str);// 左(前)补0
	        // sb.append(str).append("0");//右(后)补0
	           str = sb.toString();
	           strLen = str.length();
	        }
		}
	     
	    DateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
	    String strTmp = format.format(new Date());
	    int i= new Random().nextInt(900)+100;
	    return strTmp+Integer.toString(i)+str;
	 }
	
}
